package com.netty.learn.udpdemo;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpServer {
	
	private final int MAX_LENGTH = 1024; //最大接受字节长度
	private final int PORT_NUM = 5066; // port号
	//用于存放接收数据的字节数组
	private byte[] receMsgs = new byte[MAX_LENGTH];
	//数据报套接字
	private DatagramSocket datagramSocket;
	//用以接受数据报
	private DatagramPacket datagramPacket;
	
	public UdpServer() {
		
		try {
			//创建一个数据报套接字，并将其绑定到指定port上
			datagramSocket = new DatagramSocket(PORT_NUM);
			datagramPacket = new DatagramPacket(receMsgs, receMsgs.length);
			//等待接受udp数据报
			datagramSocket.receive(datagramPacket);
			
			//解析数据报
			String receStr = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
			System.out.println("Server Rece: " + receStr);
			System.out.println("Server Port" + datagramPacket.getPort());
			
			/**返回数据报**/
			//组装数据报
			byte[] buf = "I receive the message".getBytes();
			DatagramPacket sendPacket = new DatagramPacket(buf, buf.length, datagramPacket.getAddress(), datagramPacket.getPort());
			
			datagramSocket.send(sendPacket);
		} catch (Exception e) {
			// TODO: handle exception
        } finally {
			if (datagramSocket != null) {
				datagramSocket.close();
			}
		}
		
	}
	
	public static void main(String[] args) {
		new UdpServer();
	}
	

}
